///
/// 开关组件
/// 参照Element UI的Switch控件实现

import 'package:flutter/material.dart';
import '../../core/elegance_theme.dart';
import '../../core/elegance_base.dart';

/// 开关大小类型枚举
enum ESwitchSize {
  /// 小型开关
  small,
  
  /// 普通大小开关
  normal,
}

/// ESwitch组件
class ESwitch extends EleganceStatefulWidget {
  /// 创建ESwitch组件
  const ESwitch({
    super.key,
    required this.value,
    this.onChanged,
    this.size = ESwitchSize.normal,
    this.disabled = false,
    this.activeColor,
    this.inactiveColor,
    this.activeText,
    this.inactiveText,
    this.activeValue = true,
    this.inactiveValue = false,
    this.loading = false,
    this.width,
    this.height,
  });

  /// 当前开关的值
  final bool value;
  
  /// 状态变更回调
  final ValueChanged<bool>? onChanged;
  
  /// 开关大小
  final ESwitchSize size;
  
  /// 是否禁用
  final bool disabled;
  
  /// 打开时的背景色
  final Color? activeColor;
  
  /// 关闭时的背景色
  final Color? inactiveColor;
  
  /// 打开时的文本
  final String? activeText;
  
  /// 关闭时的文本
  final String? inactiveText;
  
  /// 打开时的值（默认为true）
  final bool activeValue;
  
  /// 关闭时的值（默认为false）
  final bool inactiveValue;
  
  /// 是否处于加载状态
  final bool loading;
  
  /// 自定义宽度
  final double? width;
  
  /// 自定义高度
  final double? height;

  @override
  State<ESwitch> createState() => _ESwitchState();
}

class _ESwitchState extends EleganceState<ESwitch> {
  /// 是否处于悬浮状态
  bool _isHovered = false;
  
  /// 是否处于按下状态
  bool _isPressed = false;
  
  @override
  void initState() {
    super.initState();
  }
  
  @override
  void didUpdateWidget(covariant ESwitch oldWidget) {
    super.didUpdateWidget(oldWidget);
  }
  
  /// 处理点击事件
  void _handleTap() {
    if (!widget.disabled && !widget.loading && widget.onChanged != null) {
      widget.onChanged!(!widget.value);
    }
  }
  
  /// 获取开关宽度
  double _getSwitchWidth() {
    if (widget.width != null) {
      return widget.width!;
    }
    
    switch (widget.size) {
      case ESwitchSize.small:
        return 40.0;
      case ESwitchSize.normal:
      default:
        return 46.0;
    }
  }
  
  /// 获取开关高度
  double _getSwitchHeight() {
    if (widget.height != null) {
      return widget.height!;
    }
    
    switch (widget.size) {
      case ESwitchSize.small:
        return 20.0;
      case ESwitchSize.normal:
      default:
        return 24.0;
    }
  }
  
  /// 获取滑块直径
  double _getThumbDiameter() {
    final height = _getSwitchHeight();
    return height - 2.0; // 减去边框宽度
  }
  
  /// 获取文本字体大小
  double _getTextFontSize() {
    switch (widget.size) {
      case ESwitchSize.small:
        return 10.0;
      case ESwitchSize.normal:
      default:
        return 12.0;
    }
  }
  
  /// 获取激活颜色
  Color _getActiveColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return theme.primaryDisabled;
    }
    
    return widget.activeColor ?? theme.primaryColor;
  }
  
  /// 获取非激活颜色
  Color _getInactiveColor(EleganceThemeData theme) {
    if (widget.disabled) {
      return theme.borderColor;
    }
    
    return widget.inactiveColor ?? theme.borderColor;
  }
  
  /// 获取滑块颜色
  Color _getThumbColor() {
    return Colors.white;
  }
  
  /// 获取文本颜色
  Color _getTextColor() {
    return Colors.white;
  }
  
  /// 构建开关组件
    @override
    Widget build(BuildContext context) {
      final theme = EleganceTheme.of(context);
      final width = _getSwitchWidth();
      final height = _getSwitchHeight();
      final thumbDiameter = _getThumbDiameter();
      final textFontSize = _getTextFontSize();
      final activeColor = _getActiveColor(theme);
      final inactiveColor = _getInactiveColor(theme);
      final thumbColor = _getThumbColor();
      final textColor = _getTextColor();
    
    // 计算滑块位置
    final thumbPosition = widget.value ? width - thumbDiameter - 1.0 : 1.0;
    
    // 构建文本
    Widget? textWidget;
    if (widget.activeText != null || widget.inactiveText != null) {
      final text = widget.value ? widget.activeText : widget.inactiveText;
      if (text != null && text.isNotEmpty) {
        textWidget = Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: textFontSize,
            fontWeight: FontWeight.normal,
          ),
        );
      }
    }
    
    // 构建加载图标
    Widget? loadingWidget;
    if (widget.loading) {
      loadingWidget = SizedBox(
        width: thumbDiameter * 0.6,
        height: thumbDiameter * 0.6,
        child: CircularProgressIndicator(
          strokeWidth: 2.0,
          valueColor: AlwaysStoppedAnimation<Color>(widget.value ? activeColor : inactiveColor),
        ),
      );
    }
    
    // 构建滑块
    final thumbWidget = Container(
      width: thumbDiameter,
      height: thumbDiameter,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: thumbColor,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 2.0,
            offset: const Offset(0, 1),
          ),
        ],
      ),
      child: loadingWidget != null
          ? Center(child: loadingWidget)
          : null,
    );
    
    // 构建开关背景
    final switchWidget = Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(height / 2),
        color: widget.value ? activeColor : inactiveColor,
        border: Border.all(
          color: widget.disabled ? theme.borderColor : Colors.transparent,
          width: 1.0,
        ),
      ),
      child: Stack(
        alignment: Alignment.center,
        children:
          textWidget != null
            ? [
                textWidget,
                Positioned(
                  left: thumbPosition,
                  child: thumbWidget,
                ),
              ]
            : [
                Positioned(
                  left: thumbPosition,
                  child: thumbWidget,
                ),
              ],
      ),
    );
    
    // 添加事件处理和状态
    return MouseRegion(
      onEnter: (_) {
        if (!widget.disabled && !widget.loading) {
          setState(() {
            _isHovered = true;
          });
        }
      },
      onExit: (_) {
        if (!widget.disabled && !widget.loading) {
          setState(() {
            _isHovered = false;
            _isPressed = false;
          });
        }
      },
      cursor: (widget.disabled || widget.loading) ? MouseCursor.defer : SystemMouseCursors.click,
      child: GestureDetector(
        onTapDown: (_) {
          if (!widget.disabled && !widget.loading) {
            setState(() {
              _isPressed = true;
            });
          }
        },
        onTapUp: (_) {
          if (!widget.disabled && !widget.loading) {
            setState(() {
              _isPressed = false;
            });
          }
        },
        onTapCancel: () {
          if (!widget.disabled && !widget.loading) {
            setState(() {
              _isPressed = false;
            });
          }
        },
        onTap: _handleTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          transform: Matrix4.identity()
            ..scale(_isPressed ? 0.95 : 1.0),
          child: switchWidget,
        ),
      ),
    );
  }
}

/// ESwitchGroup组件 - 用于管理一组开关
class ESwitchGroup extends EleganceStatefulWidget {
  /// 创建ESwitchGroup组件
  const ESwitchGroup({
    super.key,
    this.value = const [],
    this.onChanged,
    this.children,
    this.disabled = false,
    this.min = 0,
    this.max = 999999,
    this.size,
  });
  
  /// 当前选中的值列表
  final List<bool> value;
  
  /// 值变更回调
  final ValueChanged<List<bool>>? onChanged;
  
  /// 子组件（通常是多个ESwitch）
  final List<Widget>? children;
  
  /// 是否禁用整个开关组
  final bool disabled;
  
  /// 可被激活的最小数量
  final int min;
  
  /// 可被激活的最大数量
  final int max;
  
  /// 开关大小
  final ESwitchSize? size;
  
  @override
  State<ESwitchGroup> createState() => _ESwitchGroupState();
}

class _ESwitchGroupState extends EleganceState<ESwitchGroup> {
  @override
  void initState() {
    super.initState();
  }
  
  @override
  void didUpdateWidget(covariant ESwitchGroup oldWidget) {
    super.didUpdateWidget(oldWidget);
  }
  
  /// 处理子组件的值变更
  void _handleSwitchChanged(bool value, int index) {
    final newValue = List<bool>.from(widget.value);
    
    // 确保列表长度足够
    while (newValue.length <= index) {
      newValue.add(false);
    }
    
    if (value) {
      // 如果要激活，且当前激活数量小于最大值，则激活
      if (newValue.where((v) => v).length < widget.max) {
        newValue[index] = true;
      }
    } else {
      // 如果要禁用，且当前激活数量大于最小值，则禁用
      if (newValue.where((v) => v).length > widget.min) {
        newValue[index] = false;
      }
    }
    
    if (widget.onChanged != null) {
      widget.onChanged!(newValue);
    }
  }
  
  @override
  Widget build(BuildContext context) {
    // 提供SwitchGroup的InheritedWidget给子组件
    return _ESwitchGroupProvider(
      value: widget.value,
      onChanged: _handleSwitchChanged,
      disabled: widget.disabled,
      size: widget.size,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: widget.children ?? [],
      ),
    );
  }
}

/// ESwitchGroup的InheritedWidget实现，用于向下传递值和回调
class _ESwitchGroupProvider extends InheritedWidget {
  const _ESwitchGroupProvider({
    required super.child,
    required this.value,
    required this.onChanged,
    required this.disabled,
    this.size,
  });
  
  final List<bool> value;
  final void Function(bool, int) onChanged;
  final bool disabled;
  final ESwitchSize? size;
  
  @override
  bool updateShouldNotify(_ESwitchGroupProvider oldWidget) {
    return value != oldWidget.value || 
           onChanged != oldWidget.onChanged || 
           disabled != oldWidget.disabled ||
           size != oldWidget.size;
  }
  
  // 静态方法，用于子组件获取SwitchGroup的值和回调
  static _ESwitchGroupProvider? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<_ESwitchGroupProvider>();
  }
}

/// ESwitchButton组件 - 带标签的开关
class ESwitchButton extends StatelessWidget {
  /// 创建ESwitchButton组件
  const ESwitchButton({
    super.key,
    required this.value,
    required this.onChanged,
    required this.label,
    this.size = ESwitchSize.normal,
    this.disabled = false,
    this.activeColor,
    this.inactiveColor,
    this.activeText,
    this.inactiveText,
    this.loading = false,
    this.width,
    this.height,
  });

  /// 当前开关的值
  final bool value;
  
  /// 状态变更回调
  final ValueChanged<bool>? onChanged;
  
  /// 标签文本
  final String label;
  
  /// 开关大小
  final ESwitchSize size;
  
  /// 是否禁用
  final bool disabled;
  
  /// 打开时的背景色
  final Color? activeColor;
  
  /// 关闭时的背景色
  final Color? inactiveColor;
  
  /// 打开时的文本
  final String? activeText;
  
  /// 关闭时的文本
  final String? inactiveText;
  
  /// 是否处于加载状态
  final bool loading;
  
  /// 自定义宽度
  final double? width;
  
  /// 自定义高度
  final double? height;
  


  @override
  Widget build(BuildContext context) {
    final theme = EleganceTheme.of(context);
    final switchGroupProvider = _ESwitchGroupProvider.of(context);
    
    // 如果在SwitchGroup中，则使用Group的属性
    final isDisabled = switchGroupProvider?.disabled ?? disabled;
    final switchSize = switchGroupProvider?.size ?? size;
    
    // 构建标签文本样式
    final textStyle = TextStyle(
      fontSize: theme.textStyle.fontSize,
      color: isDisabled ? theme.textPlaceholderColor : theme.textSecondaryColor,
    );

    return Container(
      margin: const EdgeInsets.all(4.0),
      child: InkWell(
        onTap: isDisabled || loading ? null : () => onChanged?.call(!value),
        borderRadius: BorderRadius.circular(4.0),
        splashColor: theme.primaryColor.withOpacity(0.1),
        hoverColor: theme.primaryColor.withOpacity(0.05),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            ESwitch(
              value: value,
              onChanged: onChanged,
              size: switchSize,
              disabled: isDisabled,
              activeColor: activeColor,
              inactiveColor: inactiveColor,
              activeText: activeText,
              inactiveText: inactiveText,
              loading: loading,
              width: width,
              height: height,
            ),
            const SizedBox(width: 8.0),
            Text(label, style: textStyle),
          ],
        ),
      ),
    );
  }
}